/**
 * idee gefunden bei:
 * http://stackoverflow.com/questions/5422001/jquery-infinite-loop-for-function
 */

var delayTime = 2000;
var i = -1;
var l;

(function($) {
	$.fn.seqfx = function() {
		var elements = this;
		l = elements.length;
		var links = $("#photoTourHorizontal img");

		function execute() {

			i = (i + 1) % l;
			var currentLink = $(links[i]);

			var current = $(elements[i]);

			currentLink.fadeTo(400, 1).delay(delayTime).fadeTo(300, 0.5);

			current.fadeIn(400).delay(delayTime).fadeOut(300, execute);

		}
		execute();
		return this;
	};
}(jQuery));

function runGallery() {

	// registers the click handler on all small images
	$("#photoTourHorizontal img").click(function() {

		$("#slideshow img").stop(true, true);
		// hides all
		$("#slideshow img").hide();

		// ties to find the big image based on $(this).id and fades it in
		$(this).fadeTo(400, 1);
		var myId = $(this).attr('id');
		var slideshowImg = "#slideshow".concat(myId);
		$("#slideshow").find(slideshowImg).fadeIn(400);
	});

	// registers the fadeIn on mouseenter
	$("#photoTourHorizontal img").mouseenter(function() {
		$(this).fadeTo(400, 1);

	});

	// registers the fadeOut on mouseout
	$("#photoTourHorizontal img").mouseout(function() {
		$(this).fadeTo(400, 0.5);

	});

	// register pause event
	$("#pause").click(function() {
		// stops all running animations in fx queue
		$("#slideshow img").stop(true, true);
	});

	// register "play" event
	$("#play").click(function() {
		// stops all running animations in fx queue
		$("#slideshow img").stop(true, true);
		$("#slideshow img").hide();
		$("#slideshow img").seqfx();
	});

	// register "next" event
	$("#next").click(function() {
		$("#slideshow img").stop(true, true);
		$("#slideshow img").hide();
		i = (i + 1) % l;
		var elements = $("#slideshow img");
		$(elements[i]).fadeIn(400);
	});

	// register "previous" event
	$("#previous").click(function() {
		$("#slideshow img").stop(true, true);
		$("#slideshow img").hide();
		i = (i + l - 1) % l;
		var elements = $("#slideshow img");
		$(elements[i]).fadeIn(400);
	});

	// starts the slideshow
	$("#slideshow img").seqfx();
}

function registerMultitouch() {
	$.touch.triggerMouseEvents = true;

	$.touch.ready(function() {
		$("#slideshow").touchable({
			gesture : function(e, touchHistory) {
				// simple gesture handler
				if (touchHistory.match({
					finger : 0,
					deltaX : '<-300',
					time : '1..100'
				})) {
					$("#slideshow img").stop(true, true);
					$("#slideshow img").hide();
					i = (i + 1) % l;
					var elements = $("#slideshow img");
					$(elements[i]).fadeIn(400);
				} else if (touchHistory.match({
					finger : 0,
					deltaX : '>300',
					time : '1..100'
				})) {
					$("#slideshow img").stop(true, true);
					$("#slideshow img").hide();
					i = (i + l - 1) % l;
					var elements = $("#slideshow img");
					$(elements[i]).fadeIn(400);
				}
			}
		});
	});
	$.touch.preventDefault = false;

}